import { debounce } from '@/utils'
import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated } from 'vue'

export function useResize(resizeCallback) {
  const sidebarElm = ref(null)
  const resizeHandler = ref(null)

  // 初始化resize事件处理函数
  function initResizeEvent() {
    if (resizeHandler.value) {
      window.addEventListener('resize', resizeHandler.value)
    }
  }

  // 销毁resize事件
  function destroyResizeEvent() {
    if (resizeHandler.value) {
      window.removeEventListener('resize', resizeHandler.value)
    }
  }

  // 侧边栏尺寸变化处理函数
  function sidebarResizeHandler(e) {
    if (e.propertyName === 'width') {
      resizeHandler.value()
    }
  }

  // 初始化侧边栏resize事件
  function initSidebarResizeEvent() {
    sidebarElm.value = document.getElementsByClassName('sidebar-container')[0]
    sidebarElm.value && sidebarElm.value.addEventListener('transitionend', sidebarResizeHandler)
  }

  // 销毁侧边栏resize事件
  function destroySidebarResizeEvent() {
    sidebarElm.value && sidebarElm.value.removeEventListener('transitionend', sidebarResizeHandler)
  }

  // 初始化
  onMounted(() => {
    resizeHandler.value = debounce(resizeCallback, 100)
    initResizeEvent()
    initSidebarResizeEvent()
  })

  // 销毁时清理事件
  onBeforeUnmount(() => {
    destroyResizeEvent()
    destroySidebarResizeEvent()
  })

  // 处理keep-alive缓存的情况
  onActivated(() => {
    initResizeEvent()
    initSidebarResizeEvent()
  })

  onDeactivated(() => {
    destroyResizeEvent()
    destroySidebarResizeEvent()
  })

  return {
    initResizeEvent,
    destroyResizeEvent,
    initSidebarResizeEvent,
    destroySidebarResizeEvent
  }
}
